import { Directive, Input, TemplateRef, ViewContainerRef } from "@angular/core";
import { NzSafeAny } from "ng-zorro-antd/core/types";

/**
 * @see https://syntaxfix.com/question/2636/how-to-declare-a-variable-in-a-template-in-angular
 * 
 */
@Directive({
	selector: '[appVar]',
})
export class VarDirective {
	@Input()
	set ngVar(context: unknown) {
		this.context.$implicit = this.context.ngVar = context;

		if (!this.hasView) {
			this.vcRef.createEmbeddedView(this.templateRef, this.context);
			this.hasView = true;
		}
	}

	private context: {
		$implicit: unknown;
		ngVar: unknown;
	} = {
			$implicit: null,
			ngVar: null,
		};

	private hasView = false;

	constructor(
		private templateRef: TemplateRef<NzSafeAny>,
		private vcRef: ViewContainerRef
	) { }
}